/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.gbvbahia.vendas.beans;

import br.com.gbvbahia.vendas.controllers.util.StringBeanUtils;
import br.com.gbvbahia.vendas.modelos.Cliente;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author guilherme
 */
@Stateless
public class ClienteFacade extends AbstractFacade<Cliente> {

    @PersistenceContext(unitName = "VendasPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ClienteFacade() {
        super(Cliente.class);
    }

    public List<Cliente> buscarClientesPorTelefone(String telefone, String nome, int[] range) {
        Query q = em.createNamedQuery("Cliente.buscarClientesPorTelefone");
        q.setParameter("telefone", StringBeanUtils.acertaNomeParaLike(telefone, StringBeanUtils.LIKE_END));
        q.setParameter("telefone2", StringUtils.isBlank(telefone) ? "todos" : "filtro");
        q.setParameter("nome", StringBeanUtils.acertaNomeParaLike(nome, StringBeanUtils.LIKE_END));
        q.setParameter("nome2", StringUtils.isBlank(nome) ? "todos" : "filtro");
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int contarClientesPorTelefone(String telefone, String nome) {
        Query q = em.createNamedQuery("Cliente.contarClientesPorTelefone");
        q.setParameter("telefone", StringBeanUtils.acertaNomeParaLike(telefone, StringBeanUtils.LIKE_END));
        q.setParameter("telefone2", StringUtils.isBlank(telefone) ? "todos" : "filtro");
        q.setParameter("nome", StringBeanUtils.acertaNomeParaLike(nome, StringBeanUtils.LIKE_END));
        q.setParameter("nome2", StringUtils.isBlank(nome) ? "todos" : "filtro");
        return ((Long) q.getSingleResult()).intValue();
    }
}
